package com.recharge.service.impl;

import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.recharge.common.util.*;
import com.recharge.core.entity.*;
import com.recharge.core.mapper.GoodsGroupMapper;
import com.recharge.core.mapper.QcellcoreMapper;
import com.recharge.domain.vo.*;
import com.recharge.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.core.mapper.GoodsMapper;
import com.recharge.domain.query.GoodsQueryDO;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author reagan
 * @since 2020-08-19
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, GoodsEntity> implements GoodsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private GoodsGroupService goodsGroupService;

    @Autowired
    private QcellcoreMapper qcellcoreMapper;

    @Autowired
    private GoodsMerchantService goodsMerchantService;

    @Autowired
    private GoodsProviderService goodsProviderService;

    @Autowired
    private RouteFilterService routeFilterService;

    @Autowired
    private RedisUtil redisUtil;


    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO add(GoodsDO domain) {

        GoodsEntity entity = new GoodsEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        Integer count = -1;
        try {
            count = baseMapper.selectCount(Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getTitle, entity.getTitle()).eq(GoodsEntity::getIsDelete, Constant.IS_DELETE_FALSE));
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        if(count != null && count >= 1){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_ADD_EXIST_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_ADD_EXIST_ERROR.getCode() + " msg" + ErrorCode.GOODS_ADD_EXIST_ERROR.getMsg());
            return result;
        }

        entity.setCreateDate(Calendar.getInstance().getTime());
        entity.setModifiDate(entity.getCreateDate());
        entity.setModifier(entity.getCreator());
        entity.setDenomination(entity.getDenomination()* 1000);

        boolean res = false;
        try {
            res = this.save(entity);
        } catch(Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_ADD_ERROR.getCode() + " msg" + ErrorCode.GOODS_ADD_ERROR.getMsg());
            return result;
        }


        return result;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO addBatch(List<GoodsDO> domainList, String userName) {

        ResultDO result = new ResultSupport();

        List<GoodsEntity> addList = new ArrayList<>();
        for (GoodsDO domain : domainList) {
            GoodsEntity entity = new GoodsEntity();
            result = BeanUtilsExtends.copy(entity, domain);
            if (!result.isSuccess()) {
                logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                return result;
            }
            entity.setCreator(userName);
            entity.setCreateDate(Calendar.getInstance().getTime());
            entity.setModifiDate(entity.getCreateDate());
            entity.setModifier(entity.getCreator());
            entity.setDenomination(entity.getDenomination()* 1000);
            addList.add(entity);
        }
        if(addList ==null || addList.size() <=0){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_ADD_ERROR.getCode() + " msg" + ErrorCode.GOODS_ADD_ERROR.getMsg());
            return result;
        }
        boolean res = false;
        try {
            res = this.saveBatch(addList);
        } catch(Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_ADD_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_ADD_ERROR.getCode() + " msg" + ErrorCode.GOODS_ADD_ERROR.getMsg());
            return result;
        }
        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    @Override
    public ResultDO updateStatus(String id, int status, String modifier) {

        ResultDO result = new ResultSupport();

        GoodsEntity entity = new GoodsEntity();
//        entity.setId(id);
        try {
            entity = this.getById(id);
            entity.setStatus(status);
            entity.setModifier(modifier);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_EDIT_ERROR.getCode() + " msg" + ErrorCode.GOODS_EDIT_ERROR.getMsg());
            return result;
        }

        if(status == Constant.BUSINESS_GOODS_STATUS_1) {
            GoodsDO domain = getDomain(entity);

            redisUtil.set(Constant.GOODS_INFO + ":" + domain.getGoodsNo(), domain);
        } else if(status == Constant.BUSINESS_GOODS_STATUS_0){
            redisUtil.del(Constant.GOODS_INFO + ":" + entity.getGoodsNo());
        }
        return result;
    }

    @Override
    public ResultDO updateStatusByGroupId(String groupId, int status, String userName) {

        ResultDO result = new ResultSupport();

        GoodsEntity entity = new GoodsEntity();
        entity.setStatus(status);
        entity.setModifier(userName);
        entity.setModifiDate(Calendar.getInstance().getTime());
        boolean res = false;
        try {
            res = this.update(entity, Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getGroupId, groupId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_EDIT_ERROR.getCode() + " msg" + ErrorCode.GOODS_EDIT_ERROR.getMsg());
            return result;
        }

        return result;
    }

//    @Override
//    public ResultDO updateGoodsByGroupId(String groupId, Float discount, String userName) {
//
//        ResultDO result = new ResultSupport();
//
//        GoodsEntity entity = new GoodsEntity();
//        entity.setDiscount(discount);
//        entity.setModifier(userName);
//        entity.setModifiDate(Calendar.getInstance().getTime());
////        //如果折扣不为空
////        entity.setPrice((long)ArithUtils.mul((double)entity.getDenomination(),discount));
//        boolean res = false;
//        try {
//            res = this.update(entity, Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getGroupId, groupId));
//        } catch (Exception e) {
//        //如果没有修改的商品则表示该商品组下没有商品
//        if(!res) {
//            result.setSuccess(false);
//            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
//            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
//            return result;
//        }
//        //如果没有修改的商品则表示该商品组下没有商品
////        if(!res) {
////            result.setSuccess(false);
////            result.setErrorCode(ErrorCode.GOODS_EDIT_ERROR);
////            logger.debug("error code：" + ErrorCode.GOODS_EDIT_ERROR.getCode() + " msg" + ErrorCode.GOODS_EDIT_ERROR.getMsg());
////            return result;
////        }
//
//        return result;
//    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO edit(GoodsDO domain) {

        GoodsEntity entity = new GoodsEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        Integer count = -1;
        try {
            count = baseMapper.selectCount(Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getTitle, entity.getTitle()).eq(GoodsEntity::getIsDelete, Constant.IS_DELETE_FALSE).ne(GoodsEntity::getId, entity.getId()));
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        if(count != null && count >= 1){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_ADD_EXIST_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_ADD_EXIST_ERROR.getCode() + " msg" + ErrorCode.GOODS_ADD_EXIST_ERROR.getMsg());
            return result;
        }

        if(Constant.BUSINESS_GOODS_STATUS_1 == domain.getStatus()) {
            entity = new GoodsEntity();
            entity.setId(domain.getId());
//            entity.setDenomination(domain.getDenomination() * 1000);
        } else {
            entity.setDenomination(entity.getDenomination() * 1000);
        }
        if(domain.getRegionType() == 1){
            entity.setProvinceCode(null);
            entity.setCityCode(null);
        }
        if(domain.getRegionType() == 2){
            entity.setCityCode(null);
        }
        entity.setModifiDate(Calendar.getInstance().getTime());

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_EDIT_ERROR.getCode() + " msg" + ErrorCode.GOODS_EDIT_ERROR.getMsg());
            return result;
        }

        return result;
    }


    @Override
    public ResultDO findByGroupId(String groupId) {

        ResultDO result = new ResultSupport();

        List<GoodsEntity> goodsList = null;//

        try {
            goodsList = baseMapper.selectList(Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getGroupId, groupId).eq(GoodsEntity::getIsDelete, Constant.IS_DELETE_FALSE));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        List<GoodsDO> domainList = getDomainList(goodsList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domainList);

        return result;
    }

    @Override
    public ResultDO selectCount(GoodsDO domain) {

        GoodsEntity entity = new GoodsEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        QueryWrapper<GoodsEntity> wrapper = new QueryWrapper<GoodsEntity>(entity);

        wrapper.lambda().eq(GoodsEntity::getIsDelete, Constant.IS_DELETE_FALSE);

        Integer count = null;//

        try {
            count = baseMapper.selectCount(wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, count);
        return result;
    }

    @Override
    public ResultDO editStockById(String id, int stock) {
        GoodsEntity entity = new GoodsEntity();
        ResultDO result = new ResultSupport();
        try {
            entity = baseMapper.selectById(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        if(entity.getStock() + stock < 0){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_OUT_OF_STOCK_ERROR);
            logger.debug("库存不足");
            return result;
        }
        entity.setId(id);
        entity.setVersion(entity.getVersion());
        entity.setStock(entity.getStock() + stock);
        try {
            while (baseMapper.updateById(entity) == 0) {
                entity = baseMapper.selectById(id);
                if(entity.getStock() + stock < 0) {
                    result.setSuccess(false);
                    logger.debug("库存不足");
                    result.setErrorCode(ErrorCode.GOODS_OUT_OF_STOCK_ERROR);
                    return result;
                }
                entity.setId(id);
                entity.setVersion(entity.getVersion());
                entity.setStock(entity.getStock() + stock);
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        return result;
    }

    public ResultDO get(String id) {

        ResultDO result = new ResultSupport();
        GoodsEntity entity = null;

        try {
            entity = this.getById(id);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        GoodsDO domain = getDomain(entity);
        domain.setDenomination(entity.getDenomination() / 1000);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    public ResultDO getGoodsByGoodsNo(Integer goodsNo) {
        ResultDO result = new ResultSupport();

        QueryWrapper<GoodsEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_no", goodsNo)
                //.eq("status", Constant.BUSINESS_GOODS_STATUS_1)
                .eq("is_delete", Constant.IS_DELETE_FALSE);

        GoodsEntity entity = null;
        try {
            entity = this.baseMapper.selectOne(wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_GET_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_GET_ERROR.getCode() + " msg" + ErrorCode.PARAM_GET_ERROR.getMsg());
            return result;
        }

        if (entity == null) {
            result.setErrorCode(ErrorCode.API_GOODS_NOT_EXITE_ERROR);
            logger.debug("商品不存在");
            result.setSuccess(false);
            return result;
        }
        if(entity.getStatus() == Constant.BUSINESS_GOODS_STATUS_0) {
            result.setErrorCode(ErrorCode.API_GOODS_NOT_EXITE_ERROR);
            logger.debug("商品未上架");
            result.setSuccess(false);
            return result;
        }

        GoodsDO goodsDO = getDomain(entity);
        result.setModel(ResultDO.FIRST_MODEL_KEY, goodsDO);
        return result;
    }

    public ResultDO getGoodsByGoodsNo(Integer goodsNo, Long denomination, String rechargeNumber) {
        ResultDO result = new ResultSupport();
        GoodsDO goodsDO = (GoodsDO) redisUtil.get(Constant.GOODS_INFO + ":" + goodsNo);
        if(goodsDO == null) {
            result = getGoodsByGoodsNo(goodsNo);
            if (!result.isSuccess()) {
                return result;
            }
            goodsDO = (GoodsDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
        }

        if(goodsDO.getDenomination().longValue() != denomination.longValue()) {
            result.setErrorCode(ErrorCode.API_ORDER_DENOMINATION_ERROR);
            logger.debug("订单面值与商品金额不符合");
            result.setSuccess(false);
            return result;
        }
        QcellcoreEntity qcellcoreEntity = null;
        if (goodsDO.getType() == Constant.BUSINESS_GOODS_PHONE_FEE) {
            String phoneNo = rechargeNumber.substring(0, 7);
            try {
                qcellcoreEntity = qcellcoreMapper.selectOne(Wrappers.<QcellcoreEntity>lambdaQuery().eq(QcellcoreEntity::getPhoneNo, phoneNo));
            } catch (Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.PARAM_GET_ERROR);
                logger.debug("error code：" + ErrorCode.PARAM_GET_ERROR.getCode() + " msg" + ErrorCode.PARAM_GET_ERROR.getMsg());
                return result;
            }
            if(qcellcoreEntity == null) {
                result.setErrorCode(ErrorCode.API_ORDER_NOT_CITY_CODE);
                logger.debug("电话充值归属地的区域不匹配");
                result.setSuccess(false);
                return result;
            }
            String provinceCode = qcellcoreEntity.getAreacode().substring(0, 2);
            String cityCode = qcellcoreEntity.getAreacode().substring(2);
            goodsDO.setProvinceName(qcellcoreEntity.getProvince());
            goodsDO.setCityName(qcellcoreEntity.getCity());
            if (goodsDO.getRegionType() == 2) {
                if (goodsDO.getProvinceCode().indexOf(provinceCode) == -1) {
                    result.setErrorCode(ErrorCode.API_ORDER_NOT_CITY_CODE);
                    logger.debug("电话充值归属地与省的区域不匹配");
                    result.setSuccess(false);
                    return result;
                }
                if (StringUtils.isNotEmpty(goodsDO.getCityCode())) {
                    if (!goodsDO.getCityCode().equals(cityCode)) {
                        result.setErrorCode(ErrorCode.API_ORDER_NOT_CITY_CODE);
                        logger.debug("电话充值归属地与市的区域不匹配");
                        result.setSuccess(false);
                        return result;
                    }
                }
            }
            if(goodsDO.getServiceProvider() != qcellcoreEntity.getCompanyCode()) {
                result.setErrorCode(ErrorCode.API_ORDER_SERVICE_PROVIDER_ERROR);
                logger.debug("电话与运营商不匹配");
                result.setSuccess(false);
                return result;
            }
        }

        result.setModel(ResultDO.FIRST_MODEL_KEY, goodsDO);
        return result;
    }

    public ResultDO getGoodsChannel(OrderDO order) {

        ResultDO result = goodsProviderService.getProviderGoodsId(order.getGoodsId());

        if(!result.isSuccess()) {
            GoodsChannelDO goodsChannelDO = new GoodsChannelDO();
            result.setModel(ResultDO.FIRST_MODEL_KEY, goodsChannelDO);
            logger.debug("商品没配置对应的通道 error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        List<GoodsChannelDO> goodsChannelDOList = new ArrayList<>();
        List<Map<String, Object>> goodsProviderList = null;

        goodsProviderList = (List<Map<String, Object>>) result.getModel(ResultDO.FIRST_MODEL_KEY);
        for(Map<String, Object> map : goodsProviderList) {
            GoodsChannelDO goodsChannelDO = new GoodsChannelDO();
            goodsChannelDO.setServiceProvider(order.getServiceProvider());
            goodsChannelDO.setRechargeNumber(order.getRechargeNumber());
            goodsChannelDO.setAmount(order.getAmount());
            goodsChannelDO.setProviderMethod((Integer) map.get("provider_method"));
            goodsChannelDO.setProviderId((String) map.get("provider_id"));
            goodsChannelDO.setProviderName((String) map.get("provider_name"));
            goodsChannelDO.setProviderNo((String) map.get("provider_no"));
            goodsChannelDO.setUserId((String) map.get("user_id"));
            goodsChannelDO.setPrivateKey((String) map.get("private_key"));
            goodsChannelDO.setRequestUrl((String) map.get("request_url"));
            goodsChannelDO.setCallback((String) map.get("callback"));
            goodsChannelDO.setProviderGoodsNo((String)map.get("provider_goods_no"));
            if (map.get("priority") != null) {
                goodsChannelDO.setPriority((Integer) map.get("priority"));
            } else {
                goodsChannelDO.setPriority(0);
            }
            goodsChannelDO.setCostDiscount((Float) map.get("cost_discount"));
            goodsChannelDO.setInterfaceNum((Integer)map.get("interface_num"));
            goodsChannelDOList.add(goodsChannelDO);
        }

        //goodsChannelDOList = goodsChannelDOList.stream().sorted(Comparator.comparing(GoodsChannelDO::getCostDiscount)).collect(Collectors.toList());
        goodsChannelDOList = goodsChannelDOList.stream().sorted(Comparator.comparing(GoodsChannelDO::getPriority).reversed()).collect(Collectors.toList());
        result.setModel(ResultDO.FIRST_MODEL_KEY, goodsChannelDOList);
        return result;
    }


    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO remove(String id, String modifier) {
        //删除商品对商品组的关联
        ResultDO result = goodsGroupService.batchDisassociate(id, new String[] {id}, modifier);
        if(!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        //删除商品对供应商的关联
        result = goodsProviderService.removeByGoodsId(id, modifier);
        if(!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            if(ErrorCode.SYSTEM_EXCEPTION.getCode() == result.getErrorCode().getCode()){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        //删除商品对代理商的关联
        result = goodsMerchantService.removeByGoodsId(id, modifier);
        if(!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            if(ErrorCode.SYSTEM_EXCEPTION.getCode() == result.getErrorCode().getCode()){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        GoodsEntity entity = new GoodsEntity();
        entity.setId(id);
        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setIsDelete(Constant.IS_DELETE);
        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_DELETE_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_DELETE_ERROR.getCode() + " msg" + ErrorCode.GOODS_DELETE_ERROR.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO removeList(String[] goodsIds, String modifier) {
        ResultDO result = new ResultSupport();
        if(goodsIds == null || goodsIds.length <=0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_LIST_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_LIST_ERROR.getCode() + " msg" + ErrorCode.PARAM_LIST_ERROR.getMsg());
            return result;
        }
        for(String item:goodsIds){
            result = this.remove(item, modifier);
            if(!result.isSuccess()){
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.GOODS_DELETE_ERROR);
                logger.debug("error code：" + ErrorCode.GOODS_DELETE_ERROR.getCode() + " msg" + ErrorCode.GOODS_DELETE_ERROR.getMsg());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    @Override
    public ResultDO removeByGroupId(String groupId, String modifier) {
        ResultDO result = new ResultSupport();
        List<GoodsEntity> list = baseMapper.selectList(Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getGroupId, groupId));
        if(list != null && !list.isEmpty()){
            for(GoodsEntity item : list){
                result = this.remove(item.getId(), modifier);
                if(!result.isSuccess()){
                    result.setSuccess(false);
                    result.setErrorCode(ErrorCode.GOODS_DELETE_ERROR);
                    logger.debug("error code：" + ErrorCode.GOODS_DELETE_ERROR.getCode() + " msg" + ErrorCode.GOODS_DELETE_ERROR.getMsg());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
            }
        }
        return result;
    }

    @Override
    public ResultDO updateGoodsBatchById(GoodsDO domain, List<String> ids) {

        GoodsEntity entity = new GoodsEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        if(ids == null || ids.isEmpty()){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        List<GoodsEntity> updateList = new ArrayList<GoodsEntity>();
        ids.stream().forEach( item -> {
            GoodsEntity newEntity = new GoodsEntity();
            boolean flog = BeanUtilsExtends.copyProperties(newEntity, domain);
            newEntity.setId(item);
            if(flog){
                updateList.add(newEntity);
            }
        });
        boolean res = false;
        try {
            res = this.updateBatchById(updateList);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        return result;
    }

    public ResultDO listall() {

        ResultDO result = new ResultSupport();

        List<GoodsEntity> list = null;

        try {
            list = this.baseMapper.selectList(Wrappers.<GoodsEntity>lambdaQuery()
                    .eq(GoodsEntity::getIsDelete, Constant.IS_DELETE_FALSE)
                    .eq(GoodsEntity::getStatus, Constant.BUSINESS_GOODS_STATUS_1));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<GoodsDO> doList = getDomainList(list);
        if(doList == null) {
            result.setSuccess(false);
            return result;
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
    }



    public ResultDO find(GoodsQueryDO query) {

        GoodsEntity queryEntity = new GoodsEntity();
        ResultDO result = new ResultSupport();
        QueryWrapper<GoodsEntity> wrapper = new QueryWrapper<GoodsEntity>(queryEntity);
        //有效的
        wrapper.lambda().eq(GoodsEntity::getIsDelete, Constant.IS_DELETE_FALSE);

        //商品组筛选未绑定的和当前商品组的
        if(query.getIsRelevance() != null && query.getIsRelevance() == 0){
            queryEntity.setGroupId(null);
            //根据商品组查询商品的条件
            if(StringUtils.isNotEmpty(query.getGroupId())){
                wrapper.lambda().and( newWrapper -> {
                    newWrapper.and( groupIdWrapper -> {
                        groupIdWrapper.or(itemWrapper -> itemWrapper.eq(GoodsEntity::getGroupId, query.getGroupId()));
                        groupIdWrapper.or(itemWrapper -> itemWrapper.isNull(GoodsEntity::getGroupId));
                    });
                });
            }
        }
        if(StringUtils.isNotEmpty(query.getGroupId()) && query.getIsRelevance() != null && query.getIsRelevance() == 1){
            queryEntity.setGroupId(null);
            wrapper.lambda().eq(GoodsEntity::getGroupId, query.getGroupId());
        }
        if(StringUtils.isNotEmpty(query.getGroupId()) && query.getIsRelevance() == null){
            queryEntity.setGroupId(null);
            wrapper.lambda().eq(GoodsEntity::getGroupId, query.getGroupId());
        }
        //商品排序
        wrapper.lambda().orderByDesc(GoodsEntity::getGoodsNo);
        //关联供货需查询商品列表时，提供该字段，筛选掉该供货商已经关联的商品
        if(StringUtils.isNotEmpty(query.getProviderId())){
            result = goodsProviderService.listByProviderId(query.getProviderId());//.list(Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getProviderId, query.getProviderId()).eq(GoodsProviderEntity::getIsDelete, Constant.IS_DELETE_FALSE));
            if (result.isSuccess()) {
                List<GoodsProviderDO> list = (List<GoodsProviderDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
                if(list != null && !list.isEmpty()){
                    int count = 1;
                    if (list.size() % 100 == 0) {
                        count = list.size() / 100;
                    } else {
                        count = list.size() / 100 + 1;
                    }
                    List<List<GoodsProviderDO>> listAll = ListUtil.split(list, count);
                    for (List<GoodsProviderDO> li : listAll) {
                        if (li != null && !li.isEmpty()) {
                            wrapper.lambda().notIn(GoodsEntity::getId, li.stream().map(GoodsProviderDO::getGoodsId).collect(Collectors.toList()));
                        }
                    }
                }
            }
        }
        //关联代理商品时需要筛选掉一件存在的商品
        if(StringUtils.isNotEmpty(query.getMerchantId())){
            result = goodsMerchantService.listByMerchantId(query.getMerchantId());//.list(Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getProviderId, query.getProviderId()).eq(GoodsProviderEntity::getIsDelete, Constant.IS_DELETE_FALSE));
            if (result.isSuccess()) {
                List<GoodsMerchantDO> list = (List<GoodsMerchantDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
                if(list != null && !list.isEmpty()){
                    int count = 1;
                    if (list.size() % 100 == 0) {
                        count = list.size() / 100;
                    } else {
                        count = list.size() / 100 + 1;
                    }
                    List<List<GoodsMerchantDO>> listAll = ListUtil.split(list, count);
                    for (List<GoodsMerchantDO> li : listAll) {
                        if (li != null && !li.isEmpty()) {
                            wrapper.lambda().notIn(GoodsEntity::getId, li.stream().map(GoodsMerchantDO::getGoodsId).collect(Collectors.toList()));
                        }
                    }
                }
            }
        }

        //商品名称模糊查询
        if(StringUtils.isNotEmpty(query.getTitle())){
            queryEntity.setTitle(null);
            wrapper.lambda().like(GoodsEntity::getTitle, query.getTitle());
        }
        if(query.getStatus()!=null){
            queryEntity.setStatus(null);
            wrapper.lambda().eq(GoodsEntity::getStatus,query.getStatus());
        }
        if(query.getServiceProvider()!=null){
            queryEntity.setStatus(null);
            wrapper.lambda().eq(GoodsEntity::getServiceProvider,query.getServiceProvider());
        }
        if(StringUtils.isNotEmpty(query.getGoodsNo())){
            queryEntity.setGoodsNo(null);
            wrapper.lambda().like(GoodsEntity::getGoodsNo,query.getGoodsNo());
        }
        if(query.getDenomination() != null){
            queryEntity.setDenomination(null);
            wrapper.lambda().eq(GoodsEntity::getDenomination, query.getDenomination() * 1000);
        }

        Page<GoodsEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        IPage<GoodsEntity> iPage = null;

        try {
            iPage = baseMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        List<GoodsDO> doList = getDomainList(iPage.getRecords());
        if(doList != null && !doList.isEmpty()){
            doList.stream().forEach( item ->{
                item.setDenomination(item.getDenomination() / 1000);
            });
        }
        PageDO<GoodsDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    @Override
    public ResultDO findList(GoodsQueryDO query) {

        GoodsEntity queryEntity = new GoodsEntity();
        ResultDO result = new ResultSupport();
        QueryWrapper<GoodsEntity> wrapper = new QueryWrapper<GoodsEntity>(queryEntity);
        //有效的
        wrapper.lambda().eq(GoodsEntity::getIsDelete, Constant.IS_DELETE_FALSE);

        //商品组筛选未绑定的和当前商品组的
        if(query.getIsRelevance() != null && query.getIsRelevance() == 0){
            queryEntity.setGroupId(null);
            //根据商品组查询商品的条件
            if(StringUtils.isNotEmpty(query.getGroupId())){
                wrapper.lambda().and( newWrapper -> {
                    newWrapper.and( groupIdWrapper -> {
                        groupIdWrapper.or(itemWrapper -> itemWrapper.eq(GoodsEntity::getGroupId, query.getGroupId()));
                        groupIdWrapper.or(itemWrapper -> itemWrapper.isNull(GoodsEntity::getGroupId));
                    });
                });
            }
        }
        if(StringUtils.isNotEmpty(query.getGroupId()) && query.getIsRelevance() != null && query.getIsRelevance() == 1){
            queryEntity.setGroupId(null);
            wrapper.lambda().eq(GoodsEntity::getGroupId, query.getGroupId());
        }
        if(StringUtils.isNotEmpty(query.getGroupId()) && query.getIsRelevance() == null){
            queryEntity.setGroupId(null);
            wrapper.lambda().eq(GoodsEntity::getGroupId, query.getGroupId());
        }
        //商品排序
        wrapper.lambda().orderByDesc(GoodsEntity::getGoodsNo);
        //关联供货需查询商品列表时，提供该字段，筛选掉该供货商已经关联的商品
        if(StringUtils.isNotEmpty(query.getProviderId())){
            result = goodsProviderService.listByProviderId(query.getProviderId());//.list(Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getProviderId, query.getProviderId()).eq(GoodsProviderEntity::getIsDelete, Constant.IS_DELETE_FALSE));
            if (result.isSuccess()) {
                List<GoodsProviderDO> list = (List<GoodsProviderDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
                if(list != null && !list.isEmpty()){
                    int count = 1;
                    if (list.size() % 100 == 0) {
                        count = list.size() / 100;
                    } else {
                        count = list.size() / 100 + 1;
                    }
                    List<List<GoodsProviderDO>> listAll = ListUtil.split(list, count);
                    for (List<GoodsProviderDO> li : listAll) {
                        if (li != null && !li.isEmpty()) {
                            wrapper.lambda().notIn(GoodsEntity::getId, li.stream().map(GoodsProviderDO::getGoodsId).collect(Collectors.toList()));
                        }
                    }
                }
            }
        }
        //关联代理商品时需要筛选掉一件存在的商品
        if(StringUtils.isNotEmpty(query.getMerchantId())){
            result = goodsMerchantService.listByMerchantId(query.getMerchantId());//.list(Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getProviderId, query.getProviderId()).eq(GoodsProviderEntity::getIsDelete, Constant.IS_DELETE_FALSE));
            if (result.isSuccess()) {
                List<GoodsMerchantDO> list = (List<GoodsMerchantDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
                if(list != null && !list.isEmpty()){
                    int count = 1;
                    if (list.size() % 100 == 0) {
                        count = list.size() / 100;
                    } else {
                        count = list.size() / 100 + 1;
                    }
                    List<List<GoodsMerchantDO>> listAll = ListUtil.split(list, count);
                    for (List<GoodsMerchantDO> li : listAll) {
                        if (li != null && !li.isEmpty()) {
                            wrapper.lambda().notIn(GoodsEntity::getId, li.stream().map(GoodsMerchantDO::getGoodsId).collect(Collectors.toList()));
                        }
                    }
                }
            }
        }
        //商品名称模糊查询
        if(StringUtils.isNotEmpty(query.getTitle())){
            queryEntity.setTitle(null);
            wrapper.lambda().like(GoodsEntity::getTitle, query.getTitle());
        }
        if(query.getStatus()!=null){
            queryEntity.setStatus(null);
            wrapper.lambda().eq(GoodsEntity::getStatus,query.getStatus());
        }
        if(query.getServiceProvider()!=null){
            queryEntity.setStatus(null);
            wrapper.lambda().eq(GoodsEntity::getServiceProvider,query.getServiceProvider());
        }
        if(StringUtils.isNotEmpty(query.getGoodsNo())){
            queryEntity.setGoodsNo(null);
            wrapper.lambda().like(GoodsEntity::getGoodsNo,query.getGoodsNo());
        }
        if(query.getDenomination() != null){
            queryEntity.setDenomination(null);
            wrapper.lambda().eq(GoodsEntity::getDenomination, query.getDenomination() * 1000);
        }
        List<GoodsEntity> goodsList = null;
        try {
            goodsList = baseMapper.selectList(wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        List<GoodsDO> doList = getDomainList(goodsList);
        if(doList != null && !doList.isEmpty()){
            doList.stream().forEach( item ->{
                item.setDenomination(item.getDenomination() / 1000);
            });
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
    }


    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO saveRelation(String groupId, String[] goodsIds, String userName) {

        ResultDO result = new ResultSupport();

        if(StringUtils.isEmpty(groupId)) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_LIST_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_LIST_ERROR.getCode() + " msg" + ErrorCode.PARAM_LIST_ERROR.getMsg());
            return result;
        }
        if(goodsIds == null || goodsIds.length <=0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_LIST_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_LIST_ERROR.getCode() + " msg" + ErrorCode.PARAM_LIST_ERROR.getMsg());
            return result;
        }
//        if(goodsIds.length >= 1000){
//            result.setSuccess(false);
//            result.setErrorCode(ErrorCode.GOODS_OVERSTEP_MAX_NUM);
//            logger.debug("error code：" + ErrorCode.GOODS_OVERSTEP_MAX_NUM.getCode() + " msg" + ErrorCode.GOODS_OVERSTEP_MAX_NUM.getMsg());
//            return result;
//        }

        //查询该商品组已经存在的关联
        List<GoodsEntity> listGoods = null;
        try {
            listGoods = baseMapper.selectList(Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getGroupId, groupId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //如果商品组本来就没有商品关联，则直接新增到商品组中
        if(listGoods == null || listGoods.size() <= 0){
            //修改当前需要关联商品组的商品
//            try {
//                GoodsEntity entity = new GoodsEntity();
//                entity.setGroupId(groupId);
//                entity.setModifier(userName);
//                baseMapper.update(entity, Wrappers.<GoodsEntity>lambdaQuery().in(GoodsEntity::getId, Stream.of(goodsIds).collect(Collectors.toList())));
//            } catch (Exception e) {
//                result.setSuccess(false);
//                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
//                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return result;
//            }
            try {
                GoodsEntity entity = new GoodsEntity();
                entity.setGroupId(groupId);
                entity.setModifier(userName);
                for (String goodsId : goodsIds) {
                    baseMapper.update(entity, Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getId, goodsId));
                }
            } catch (Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
            return result;
        }
        List<String> newIdList = Stream.of(goodsIds).collect(Collectors.toList());
        List<String> oldIdList = listGoods.stream().map(GoodsEntity::getId).collect(Collectors.toList());
        //如果商品组存在关联
        List<String> addGoodsList = new ArrayList<>();
        addGoodsList.addAll(newIdList);
//        List<String> delGoodsList = new ArrayList<>();
//        delGoodsList.addAll(oldIdList);
        addGoodsList.removeAll(oldIdList);
//        delGoodsList.removeAll(newIdList);
        GoodsEntity updateEntity = new GoodsEntity();
        updateEntity.setModifier(userName);
        //新增和修改
        if(addGoodsList != null && addGoodsList.size() > 0){
            updateEntity.setGroupId(groupId);
            try {
                for (String goodsId : addGoodsList) {
                    baseMapper.update(updateEntity, Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getId, goodsId));
                }
            } catch (Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
//        //不做移除处理
//        if(delGoodsList != null && delGoodsList.size() > 0){
//            updateEntity.setGroupId(null);
//            try {
//                for (String goodsId : delGoodsList) {
//                    baseMapper.update(updateEntity, Wrappers.<GoodsEntity>lambdaQuery().eq(GoodsEntity::getId, goodsId));
//                }
//            } catch (Exception e) {
//                result.setSuccess(false);
//                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
//                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return result;
//            }
//        }
        //查询该商品组修改之前的关联
        List<GoodsMerchantDO> list = new ArrayList<>();
        try {
            for (String goodsId : oldIdList) {
                GoodsMerchantDO findDomain = new GoodsMerchantDO();
                findDomain.setGoodsId(goodsId);
                result = goodsMerchantService.findList(findDomain);

                if(!result.isSuccess()){
                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                    throw new Exception();
                }
                List<GoodsMerchantDO> addList = (List<GoodsMerchantDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
                if(addList != null && addList.size() >0){
                    list.addAll(addList);
                }
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

        if(list == null || list.size() <= 0){
            return result;
        }
//        oldIdList = list.stream().map(GoodsMerchantDO::getGoodsId).collect(Collectors.toList());
//        delGoodsList = new ArrayList<>();
//        delGoodsList.addAll(oldIdList);
//        addGoodsList.removeAll(oldIdList);
//        delGoodsList.removeAll(newIdList);
        if(addGoodsList != null && addGoodsList.size() > 0){
            List<String> merchantIdList = list.stream().map(GoodsMerchantDO::getMerchantId).distinct().collect(Collectors.toList());
            //查询商品组折扣
            result = goodsGroupService.get(groupId);

            if(!result.isSuccess()){
                logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }

            GoodsGroupDO finalGoodsGroup = (GoodsGroupDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
            //将商品与代理商新增到关联表中
            List<GoodsMerchantDO> entityList = new ArrayList<GoodsMerchantDO>();
            addGoodsList.stream().forEach( item -> {
                merchantIdList.stream().forEach( itemMerchant -> {
                    GoodsMerchantDO entityObj = new GoodsMerchantDO();
                    if(finalGoodsGroup == null){
                        entityObj.setDiscount(0F);
                    } else {
                        if (finalGoodsGroup.getUnit() == Constant.UNIT_SCALE) {
                            entityObj.setDiscount((float)ArithUtils.div(Double.parseDouble(String.valueOf(finalGoodsGroup.getValueData())), 10000));
                        }
                    }
                    entityObj.setMerchantId(itemMerchant);
                    entityObj.setGoodsId(item);
                    entityObj.setCreator(userName);
                    entityObj.setModifier(userName);
                    entityList.add(entityObj);
                });
            });
            result = goodsMerchantService.saveBatch(entityList);
            if(!result.isSuccess()){
                logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
//        //不做移除处理
//        if(delGoodsList != null && delGoodsList.size() > 0){
//            try {
//                GoodsMerchantDO updateDomain = new GoodsMerchantDO();
//                updateDomain.setModifier(userName);
//                updateDomain.setIsDelete(Constant.IS_DELETE);
//                for (String goodsId : delGoodsList) {
//                    result = goodsMerchantService.editByGoodsId(updateDomain, goodsId);
//                    if(!result.isSuccess()){
//                        logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
//                        throw new Exception();
//                    }
//                }
//            } catch (Exception e) {
//                result.setSuccess(false);
//                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
//                logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return result;
//            }
//        }

        return result;
    }


    @Override
    public ResultDO saveShelfBatch(Integer status, String[] goodsIds, String userName) {
        ResultDO result = new ResultSupport();
        if(goodsIds == null || goodsIds.length <=0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_LIST_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_LIST_ERROR.getCode() + " msg" + ErrorCode.PARAM_LIST_ERROR.getMsg());
            return result;
        }

        if(!(Constant.BUSINESS_GOODS_STATUS_0 == status) && !(Constant.BUSINESS_GOODS_STATUS_1 == status)) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_STATUS_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_STATUS_ERROR.getCode() + " msg" + ErrorCode.GOODS_STATUS_ERROR.getMsg());
            return result;
        }
        //循环修改商品上下架
        for (String id : goodsIds) {
            updateStatus(id, status, userName);
        }
//    	GoodsEntity entity = new GoodsEntity();
//    	entity.setStatus(Integer.parseInt(status));
//    	entity.setModifier(userName);
//    	//批量商品上下架
//    	try {
//    		baseMapper.update(entity, Wrappers.<GoodsEntity>lambdaQuery().in(GoodsEntity::getId, Stream.of(goodsIds).collect(Collectors.toList())));
//        } catch (Exception e) {
//            result.setSuccess(false);
//            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
//            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
//            return result;
//        }
        return result;
    }


    private GoodsDO getDomain(GoodsEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        GoodsDO domain = new GoodsDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<GoodsDO> getDomainList(List<GoodsEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<GoodsDO> doList = new ArrayList<GoodsDO>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(GoodsEntity entity : list) {

                GoodsDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }

}
